import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Statistic, Progress, List, Avatar, Tag, Button } from 'antd';
import {
  BookOutlined,
  ClockCircleOutlined,
  TrophyOutlined,
  FireOutlined,
  UserOutlined,
  StarOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import useAuthStore from '../../stores/authStore';
import { courseAPI } from '../../utils/api';
import './index.scss';

const Dashboard = () => {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const [stats, setStats] = useState({
    totalCourses: 0,
    completedCourses: 0,
    totalHours: 0,
    currentStreak: 0,
  });
  const [recentCourses, setRecentCourses] = useState([]);

  useEffect(() => {
    fetchDashboardData();
  }, []);

  const fetchDashboardData = async () => {
    try {
      // 获取我的课程
      const coursesResponse = await courseAPI.getMyCourses();
      const courses = coursesResponse.data || [];
      
      // 模拟统计数据
      const mockStats = {
        totalCourses: courses.length,
        completedCourses: Math.floor(courses.length * 0.6),
        totalHours: Math.floor(courses.length * 2.5),
        currentStreak: 7,
      };
      
      setStats(mockStats);
      setRecentCourses(courses.slice(0, 5));
    } catch (error) {
      console.error('Failed to fetch dashboard data:', error);
    }
  };

  const getCompletionRate = () => {
    if (stats.totalCourses === 0) return 0;
    return Math.round((stats.completedCourses / stats.totalCourses) * 100);
  };

  const renderStatsCards = () => (
    <Row gutter={[16, 16]}>
      <Col xs={12} md={6}>
        <Card>
          <Statistic
            title="总课程数"
            value={stats.totalCourses}
            prefix={<BookOutlined />}
            valueStyle={{ color: '#1890ff' }}
          />
        </Card>
      </Col>
      <Col xs={12} md={6}>
        <Card>
          <Statistic
            title="已完成"
            value={stats.completedCourses}
            prefix={<TrophyOutlined />}
            valueStyle={{ color: '#52c41a' }}
          />
        </Card>
      </Col>
      <Col xs={12} md={6}>
        <Card>
          <Statistic
            title="学习时长"
            value={stats.totalHours}
            suffix="小时"
            prefix={<ClockCircleOutlined />}
            valueStyle={{ color: '#faad14' }}
          />
        </Card>
      </Col>
      <Col xs={12} md={6}>
        <Card>
          <Statistic
            title="连续学习"
            value={stats.currentStreak}
            suffix="天"
            prefix={<FireOutlined />}
            valueStyle={{ color: '#f5222d' }}
          />
        </Card>
      </Col>
    </Row>
  );

  const renderProgressSection = () => (
    <Card title="学习进度" className="progress-card">
      <div className="overall-progress">
        <div className="progress-info">
          <h3>整体完成度</h3>
          <span className="progress-percentage">{getCompletionRate()}%</span>
        </div>
        <Progress
          percent={getCompletionRate()}
          strokeColor={{
            '0%': '#108ee9',
            '100%': '#87d068',
          }}
          strokeWidth={8}
        />
      </div>
      
      <div className="progress-actions">
        <Button type="primary" onClick={() => navigate('/courses')}>
          继续学习
        </Button>
        <Button onClick={() => navigate('/my-courses')}>
          查看全部课程
        </Button>
      </div>
    </Card>
  );

  const renderRecentCourses = () => (
    <Card title="最近学习" className="recent-courses-card">
      <List
        itemLayout="horizontal"
        dataSource={recentCourses}
        renderItem={(course) => (
          <List.Item
            actions={[
              <Button
                type="link"
                onClick={() => navigate(`/courses/${course.id}`)}
              >
                继续学习
              </Button>
            ]}
          >
            <List.Item.Meta
              avatar={
                <Avatar
                  src={course.cover_image}
                  icon={<BookOutlined />}
                  size="large"
                />
              }
              title={
                <div className="course-title">
                  {course.title}
                  <Tag color="blue" style={{ marginLeft: 8 }}>
                    {course.progress || 0}%
                  </Tag>
                </div>
              }
              description={
                <div>
                  <p>{course.description}</p>
                  <div className="course-meta">
                    <span>
                      <ClockCircleOutlined /> {course.duration}
                    </span>
                    <span>
                      <StarOutlined /> {course.rating}
                    </span>
                  </div>
                </div>
              }
            />
          </List.Item>
        )}
      />
    </Card>
  );

  const renderAchievements = () => (
    <Card title="学习成就" className="achievements-card">
      <Row gutter={[16, 16]}>
        <Col span={8}>
          <div className="achievement-item">
            <div className="achievement-icon">
              <TrophyOutlined />
            </div>
            <div className="achievement-info">
              <h4>学习达人</h4>
              <p>完成10门课程</p>
            </div>
          </div>
        </Col>
        <Col span={8}>
          <div className="achievement-item">
            <div className="achievement-icon">
              <FireOutlined />
            </div>
            <div className="achievement-info">
              <h4>坚持不懈</h4>
              <p>连续学习7天</p>
            </div>
          </div>
        </Col>
        <Col span={8}>
          <div className="achievement-item">
            <div className="achievement-icon">
              <StarOutlined />
            </div>
            <div className="achievement-info">
              <h4>优秀学员</h4>
              <p>获得5星评价</p>
            </div>
          </div>
        </Col>
      </Row>
    </Card>
  );

  return (
    <div className="dashboard-page">
      <div className="dashboard-header">
        <h1>欢迎回来，{user?.nickname || user?.username}！</h1>
        <p>继续您的学习之旅</p>
      </div>

      {renderStatsCards()}

      <Row gutter={[24, 24]} style={{ marginTop: 24 }}>
        <Col xs={24} lg={12}>
          {renderProgressSection()}
        </Col>
        <Col xs={24} lg={12}>
          {renderAchievements()}
        </Col>
      </Row>

      <div style={{ marginTop: 24 }}>
        {renderRecentCourses()}
      </div>
    </div>
  );
};

export default Dashboard; 